package com.ky.manage.activity;

import android.content.Intent;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;

import com.ky.manage.BaseApplication;
import com.ky.manage.BuildConfig;
import com.ky.manage.R;
import com.ky.manage.base.BaseActivity;
import com.ky.manage.constant.OverallData;
import com.ky.manage.model.LoginUserInfo;
import com.ky.manage.model.response.UserInfoResp;
import com.ky.manage.ui.EditTextWithPwdView;
import com.ky.manage.ui.verifyCode.VerifyCodeButton;
import com.ky.manage.utils.StringUtil;
import com.ky.manage.utils.ToastUtils;
import com.ky.manage.utils.ZyUtils;
import com.ky.manage.utils.http.AsyncHttpUtils;
import com.ky.manage.utils.http.BusinessHttpReqUtils;
import com.ky.manage.utils.log.ObjectUtil;
import com.loopj.android.http.TextHttpResponseHandler;

import cz.msebera.android.httpclient.Header;
import static com.ky.manage.utils.http.BusinessHttpReqUtils.SERVICE_DOMAIN;

/**
 * 密码登录页
 */
public class PwdLoginActivity extends BaseActivity {

    private EditText phoneEt, virificationCode;
    private VerifyCodeButton verifyCodeButton;
    private EditTextWithPwdView pwdEt;
    private View pwdLayout, verificationLayout;
    int loginType = 0; //0 pwd login,  1  code login

    @Override
    protected int getLayoutId() {
        return R.layout.activity_pwd_login;
    }

    @Override
    protected void initView() {
        findView(R.id.back_iv, v -> {
            //返回
            finish();
        });

        //pwdLayout = findView(R.id.)
        phoneEt = findView(R.id.phone_et);
        pwdEt = findView(R.id.pwd_et);
        if (BuildConfig.DEBUG) {
            phoneEt.setText("18610286791");
            pwdEt.setText("123456");
        }
        findView(R.id.ready_2_login, v -> {
            //立即登录
            if (TextUtils.isEmpty(phoneEt.getText().toString().trim()) ||
                    TextUtils.isEmpty(pwdEt.getText().toString().trim())) {
                ToastUtils.showRoundRectToast("请完善信息");
                return;
            }
            ZyUtils.getInstance().showLoadingDialog(this, "请求中，请稍候");
            if (!TextUtils.isEmpty(BusinessHttpReqUtils.getInstance().getToken())) {
                requestLoginUserInfo();
                return;
            }
            BusinessHttpReqUtils.getInstance().requestLogin(this, phoneEt.getText().toString().trim(),
                    pwdEt.getText(), new TextHttpResponseHandler(){
                        @Override
                        public void onSuccess(int statusCode, Header[] headers, String responseString) {
                            //请求成功回调
                            requestLoginUserInfo();
                        }

                        @Override
                        public void onFailure(int statusCode, Header[] headers,
                                              String responseString, Throwable throwable) {
                            //请求失败
                            ZyUtils.getInstance().hideLoadingDialog();
                        }

                    });
        });
        findView(R.id.sms_login_tv, v -> {
            //验证码登录
            if (OverallData.sEnableSmsCodeLogin) {
                finish();
                toActivity(new Intent(PwdLoginActivity.this, LoginActivity.class));
            } else {
                ToastUtils.showRoundRectToast(StringUtil.getResString(R.string.to_do_prompt));
            }
        });
        //验证码输入
        virificationCode = findView(R.id.etv_verification_code);
        //
        verifyCodeButton = findView(R.id.btn_send_virification_code);
        verifyCodeButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                verifyCodeButton.start();
                sendVerifyCode(virificationCode.getText().toString());
            }
        });
    }

    private void sendVerifyCode(String phone) {
        AsyncHttpUtils.getInstance().get(SERVICE_DOMAIN + "/" + phone, new TextHttpResponseHandler() {
            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                Log.d("lhm", "获取验证码失败：" + responseString);
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, String responseString) {

            }
        });
    }

    /**
     * 获取用户信息
     */
    public void requestLoginUserInfo() {
        BusinessHttpReqUtils.getInstance().requestLoginUserInfo(this, new TextHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, String responseString) {
                Log.d("lhm", "requestLoginUserInfo = " + responseString);
                UserInfoResp userInfoResp = BusinessHttpReqUtils.getInstance().parseJsonObj(responseString, UserInfoResp.class);
                ZyUtils.getInstance().insertLog("requestLoginUserInfo", "onSuccess responseString = "
                        + responseString);
                if (null != userInfoResp) {
                    if (userInfoResp.code == 200) {
                        LoginUserInfo loginUserInfo = new LoginUserInfo();
                        loginUserInfo.nickName = userInfoResp.data.nickName;
                        loginUserInfo.userName = userInfoResp.data.userName;
                        loginUserInfo.userId = userInfoResp.data.userId;
                        loginUserInfo.businessOutletsId = userInfoResp.data.businessOutletsId;
                        if (!TextUtils.isEmpty(userInfoResp.data.avatar)) {
                            if (userInfoResp.data.avatar.startsWith("http")) {
                                loginUserInfo.userHeadUrl = userInfoResp.data.avatar;
                            } else {
                                loginUserInfo.userHeadUrl = BusinessHttpReqUtils.SERVICE_DOMAIN + ":8888" + userInfoResp.data.avatar;
                            }
                        }
                        loginUserInfo.phone = userInfoResp.data.phonenumber;
                        loginUserInfo.pwd = pwdEt.getText().trim();
                        loginUserInfo.sex = userInfoResp.data.sex;
                        loginUserInfo.idCardValue = userInfoResp.data.numberId;
                        loginUserInfo.addressDetail = userInfoResp.data.detailAddress;
                        loginUserInfo.addressRegion = userInfoResp.data.areaName;
                        loginUserInfo.addressRegionCode = userInfoResp.data.areaCode;
                        loginUserInfo.userTypeDesc = userInfoResp.postGroup;
                        if (TextUtils.isEmpty(loginUserInfo.userTypeDesc) && null != userInfoResp.roleGroup) {
                            loginUserInfo.userTypeDesc = userInfoResp.roleGroup.split(",")[0];
                        }
                        loginUserInfo.isLogin = true;
                        ZyUtils.getInstance().insertLog("requestLoginUserInfo", "loginUserInfo = "
                                + ObjectUtil.objectToString(loginUserInfo));
                        BaseApplication.updateLoginUserInfo(loginUserInfo);
                        ToastUtils.showRoundRectToast("登陆成功");
                        finish();
                    } else if (userInfoResp.code == 401) {
                        //登陆失效，需重新登陆
                        BusinessHttpReqUtils.getInstance().autoPwdLogin(mCurActivity);
                    } else {
                        ToastUtils.showRoundRectToast("获取用户信息失败：" + userInfoResp.msg);
                    }
                } else {
                    ToastUtils.showRoundRectToast("获取用户信息失败：" + userInfoResp.msg);
                }
                ZyUtils.getInstance().hideLoadingDialog();
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                ZyUtils.getInstance().insertLog("requestLoginUserInfo", "onFailure errorResponse = "
                        + responseString);
                ToastUtils.showRoundRectToast("获取用户信息失败" + throwable.getMessage());
                ZyUtils.getInstance().hideLoadingDialog();
            }
        });
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void onResume() {
        super.onResume();
        if (BaseApplication.isValidLogin()) {
            finish();
        }
    }
}
